﻿using System.Net;
using System.Net.Http.Headers;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


using HttpClient client = new();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
client.DefaultRequestHeaders.Add("User-Agent", ".NET Foundation Repository Reporter");

string token = string.Empty;
//token = "MS4wLjABAAAACrTsBplRstZVFzNVmZG7cQQqRO2nxZ7ZPj6t4_3uyhI";//爱墅生活
//token = "MS4wLjABAAAA_z7GHxxfQLay-0sD2LMZtNOepwM6Rd0nkEYxh5GuRcg"; //静水流深1166
token = "MS4wLjABAAAAJzzWe-UpjTu4F2DoDHDB3VNUa1lAZ_rvrQriFkXv7SMJzziU8LoHezh3DLHSbHEi"; //吾非设计机构
//token = "MS4wLjABAAAAenpPjv2HSNR9KAlRvJ-QNvrdJVPDTOrfYXmRz_vVqA9lrPiYU7HTvNV77m98nG4O"; //HZJ匠人先行
string url = $"https://www.toutiao.com/api/pc/list/user/feed?category=profile_all&token={token}&max_behot_time=";



#region 测试图片保存
//string imgurl = "https://p3-sign.toutiaoimg.com/tos-cn-i-ezhpy3drpa/4a2ef7ab4954417481e26b04de356034~tplv-obj:1080:1349.image?_iz=97245&from=post&lk3s=06827d14&x-expires=1722816000&x-signature=lpxPFA1orNGxHUrhKBOOdFwSrnw%3D";
//string imgPath = await GetMethodImage(client, imgurl, "TEST", "TESTIMAGENAME-0");
//Console.WriteLine(imgPath); 
#endregion


await loadList(client, url, "0");

#region 头条帐号文章内容获取


//加载文章列表
static async Task loadList(HttpClient client, string url, string oldTime)
{
    string aUrl = url + oldTime;
    string listJson = await ProcessRepositoriesAsync(client, aUrl);
    JObject obj = JObject.Parse(listJson);
    string timestr = obj["next"]["max_behot_time"].ToString();
    Console.WriteLine();
    Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    Console.WriteLine("nowTimeStr:" + oldTime);
    Console.WriteLine("nextTimeStr:" + timestr);
    Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    showImgUrl(client, obj);
    if (obj["data"].LongCount() == 0)
    {
        return;
    }
    else
    {
        await loadList(client, url, timestr);
    }
}

//显示图片路径
static void showImgUrl(HttpClient client, JObject obj)
{
    for (int i = 0; i < obj["data"].LongCount(); i++)
    {
        MyLog.num++;
        #region 获取用户名称
        string userName = "未知-";
        if (null != obj["data"][i]["user"])
        {
            if (null != obj["data"][i]["user"]["info"] && null != obj["data"][i]["user"]["info"]["name"])
            {
                userName = obj["data"][i]["user"]["info"]["name"].ToString();
                //Console.WriteLine(userName);
            }
            if (null != obj["data"][i]["user"]["name"])
            {
                userName = obj["data"][i]["user"]["name"].ToString();
                //Console.WriteLine(userName);
            }
        }
        if (string.IsNullOrWhiteSpace(MyLog.userName))
        {
            MyLog.userName = userName;
        }
        else if (userName != MyLog.userName)
        {
            MyLog.userName = userName;
        }
        //Console.WriteLine("myLogUserName:"+MyLog.userName);

        #endregion
        if (null != obj["data"][i]["itemCell"])
        {
            if (null != obj["data"][i]["itemCell"]["threadCustom"])
            {
                Console.WriteLine("threadCustom is True");

                string wztitle = obj["data"][i]["content"].ToString();
                Console.WriteLine("wztitle:" + wztitle);
                string wzid = obj["data"][i]["id"].ToString();
                Console.WriteLine("wzid:" + wzid);
                string wzurl = "https://www.toutiao.com/w/" + wzid;
                Console.WriteLine("wzurl:" + wzurl);

                //Console.WriteLine("threadCustom:" + obj["data"][i]["itemCell"]["threadCustom"].ToString());
                //Console.WriteLine("imageList:" + obj["data"][i]["itemCell"]["threadCustom"]["largeImageList"].ToString());
                if (null != obj["data"][i]["itemCell"]["threadCustom"]["largeImageList"])
                {
                    for (int imgIndex = 0; imgIndex < obj["data"][i]["itemCell"]["threadCustom"]["largeImageList"].LongCount(); imgIndex++)
                    {
                        string imgUrl = obj["data"][i]["itemCell"]["threadCustom"]["largeImageList"][imgIndex]["url"].ToString();
                        Console.WriteLine("imgUrl:" + imgUrl);
                        try
                        {
                            GetMethodImage(client, imgUrl, MyLog.userName, wztitle + imgIndex);
                        }
                        catch (Exception e)
                        {
                            Console.BackgroundColor = ConsoleColor.Red;
                            Console.WriteLine("ERR:" + e.Message);
                            Console.BackgroundColor = ConsoleColor.White;
                            continue;
                        }
                    }
                }

            }
            else
            {
                Console.WriteLine("threadCustom is null");
            }
        }

        //string wzJson = await ProcessRepositoriesAsync(client, wzurl);
        //Console.WriteLine("wzJson:" + wzJson);

        Console.WriteLine("当前文章数量：" + MyLog.num);

        Console.WriteLine();
        Console.WriteLine("==================================================================");
        Console.WriteLine();
    }
}


#endregion

static async Task<string> ProcessRepositoriesAsync(HttpClient client,string url)
{
    var json = await client.GetStringAsync(url);
    return json;
    //Console.Write(json);
    

}

#region 保存图片

static async Task<string> GetMethodImage(HttpClient client, string imgUrl,string userName,string imageName)
{
    string pathFile = "E:\\A_Work_Documents\\头条图片/"+userName;

    //判断文件夹是否存在
    if (!Directory.Exists(pathFile))
    {
        Directory.CreateDirectory(pathFile);
    }
    pathFile += $@"/{imageName}.jpg";
    byte[] b = await GetBytesFromUrl(client, imgUrl);
    WriteBytesToFile(pathFile, b);
    return pathFile;
}

static async Task<byte[]> GetBytesFromUrl(HttpClient client,string url)
{
    byte[] b;
    HttpResponseMessage response= await client.GetAsync(url);
    Stream stream = response.Content.ReadAsStream();
    using (BinaryReader br = new BinaryReader(stream))
    {
        b = br.ReadBytes(500000);
        br.Close();
    }
    return b;

}

static void WriteBytesToFile(string fileName, byte[] content)
{
    FileStream fs = new FileStream(fileName, FileMode.Create);
    BinaryWriter w = new BinaryWriter(fs);
    try
    {
        w.Write(content);
    }
    finally
    {
        fs.Close();
        w.Close();
    }

}


#endregion

public static class MyLog
{
    public static long num = 0;
    public static readonly string savePath = "";
    public static string userName = "";
}